﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using bzxxxt.admin.entity;
using bzxxxt.admin.service;
using System.Text.RegularExpressions;

namespace bzxxxt.admin.ashx
{
    /// <summary>
    /// rm_login 的摘要说明
    /// </summary>
    public class rm_login : IHttpHandler
    {
        UserService s = new UserService();
        LoginLogService logs = new LoginLogService();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request.Params["action"];

            try
            {
                switch (action)
                {
                    case "getuser":
                        if (context.Request.IsAuthenticated)
                        {
                            FormsIdentity id = (FormsIdentity)context.User.Identity;
                            FormsAuthenticationTicket tickets = id.Ticket;

                            //反序列化获取票证里的用户对象（这个用户对象是cookie里保存的，不一定是数据库里最新的用户状态）
                            UserEntity userFromCookie = new JavaScriptSerializer().Deserialize<UserEntity>(tickets.UserData);
                            //执行登录操作（获取数据库里最新的用户对象）
                            UserEntity userFromDB = s.login(userFromCookie.userName, userFromCookie.userPwd);

                            if (userFromDB == null)   //修改了用户名或密码
                            {
                                FormsAuthentication.SignOut();   //干掉cookie
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户名或密码错误！"
                                }));
                            }
                            else if (!userFromDB.able)   //管理员禁用了这个账户
                            {
                                FormsAuthentication.SignOut();   //干掉cookie
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户已被禁用！"
                                }));
                            }
                            else if (userFromCookie.userName != userFromDB.userName)   //如果这两个字段修改了需要重新生成cookie
                            {
                                FormsAuthentication.SignOut();
                                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                                (
                                    2,
                                    userFromDB.userName,
                                    DateTime.Now,
                                    tickets.Expiration,
                                    false,
                                    new JavaScriptSerializer().Serialize(userFromDB)  //序列化新的用户对象
                                );
                                string encTicket = FormsAuthentication.Encrypt(ticket);   //加密
                                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                                if (ticket.Expiration != new DateTime(9999, 12, 31))    //不是默认时间才设置过期时间，否则会话cookie
                                    cookie.Expires = tickets.Expiration;
                                context.Response.Cookies.Add(cookie);  //写入cookie

                                //输出新对象
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = true,
                                    msg = new JavaScriptSerializer().Serialize(userFromDB)
                                }));
                            }
                            else
                            {
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = true,
                                    msg = tickets.UserData
                                }));
                            }
                        }
                        else
                        {
                            context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "nocookie"
                                }));                            
                        }
                        break;
                    case "iflogin":
                        //System.Threading.Thread.Sleep(5000);
                        if (context.Request.IsAuthenticated)
                        {
                            FormsIdentity id = (FormsIdentity)context.User.Identity;
                            FormsAuthenticationTicket tickets = id.Ticket;

                            //获取票证里序列化的用户对象（反序列化）
                            UserEntity userCheck = new JavaScriptSerializer().Deserialize<UserEntity>(tickets.UserData);
                            //执行登录操作
                            UserEntity userReLogin = s.login(userCheck.userName, userCheck.userPwd);

                            if (userReLogin == null)
                            {
                                FormsAuthentication.SignOut();
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户名或密码错误！"
                                }));
                            }
                            else if (!userReLogin.able)
                            {
                                FormsAuthentication.SignOut();
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户已被禁用！"
                                }));
                            }
                            else
                            {
                                //记录登录日志
                                string userIp = context.Request.UserHostAddress;
                                string city = context.Request.Params["city"] ?? "未知";   //访问者所处城市
                                string userName = context.User.Identity.Name;
                                new LoginLogService().add(userName, userIp, city, true);
                                
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = true,
                                    msg = "已登录过，正在跳转！！"
                                }));
                            }
                        }
                        else
                        {
                            context.Response.Write(JsonUtil.ToJson(new
                            {
                                success = false,
                                msg = "nocookie"
                            }));           
                        }
                        break;
                    case "login":
                        {
                            string userIp = context.Request.UserHostAddress;
                            string city = context.Request.Params["city"] ?? "未知";
                            string remember = context.Request.Params["remember"] ?? "";         //记住密码天数
                            string name = context.Request.Params["loginName"];
                            string pwd = context.Request.Params["loginPwd"];
                            var pwdRegex = new Regex("(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}");
                            Match m = pwdRegex.Match(pwd);
                            if (!m.Success)
                            {
                                context.Response.Write(JsonUtil.ToJson(new { success = false,
                                    msg = "密码中必须包含大小写字母、数字、特殊字符，至少8位！"
                                }));
                                break;
                            }
                            pwd = Md5.GetMD5String(pwd);  //md5加密
                            UserEntity currentUser = s.login(name, pwd);
                            if (currentUser == null)
                            {
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户名或密码错误！"
                                }));
                                logs.add(name, userIp, city, false);
                            }
                            else if (currentUser.able == false)
                            {
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户已被禁用！"
                                }));
                                logs.add(name, userIp, city, false);
                            }
                            else
                            {
                                //记录登录日志
                                logs.add(name, userIp, city, true);
                                
                                DateTime dateCookieExpires;  //cookie有效期
                                switch (remember)
                                {
                                    case "notremember":
                                        dateCookieExpires = new DateTime(9999, 12, 31);   //默认时间
                                        break;
                                    case "oneday":
                                        dateCookieExpires = DateTime.Now.AddDays(1);
                                        break;
                                    case "sevenday":
                                        dateCookieExpires = DateTime.Now.AddDays(7);
                                        break;
                                    case "onemouth":
                                        dateCookieExpires = DateTime.Now.AddDays(30);
                                        break;
                                    case "oneyear":
                                        dateCookieExpires = DateTime.Now.AddDays(365);
                                        break;
                                    default:
                                        dateCookieExpires = new DateTime(9999, 12, 31);
                                        break;
                                }
                                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                                (
                                    2,
                                    currentUser.userName,
                                    DateTime.Now,
                                    dateCookieExpires,
                                    false,
                                    new JavaScriptSerializer().Serialize(currentUser)  //序列化当前用户对象
                                );
                                string encTicket = FormsAuthentication.Encrypt(ticket);
                                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                                if (dateCookieExpires != new DateTime(9999, 12, 31))    //不是默认时间才设置过期时间，否则会话cookie
                                    cookie.Expires = dateCookieExpires;
                                context.Response.Cookies.Add(cookie);

                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = true,
                                    msg = "登录成功！"
                                }));
                            }
                            break;
                        }
                    case "ssologin":
                        {
                            string userIp = context.Request.UserHostAddress;
                            string city = "SSO "+ context.Request.Params["city"] ?? "未知";
                            string remember = context.Request.Params["remember"] ?? "";         //记住密码天数
                            string name = context.Request.Params["loginName"];
                            //string pwd = Md5.GetMD5String(context.Request.Params["loginPwd"]);  //md5加密
                            UserEntity currentUser = s.ssologin(name);
                            if (currentUser == null)
                            {
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户名或密码错误！"
                                }));
                                logs.add(name, userIp, city, false);
                            }
                            else if (currentUser.able == false)
                            {
                                context.Response.Write(JsonUtil.ToJson(new
                                {
                                    success = false,
                                    msg = "用户已被禁用！"
                                }));
                                logs.add(name, userIp, city, false);
                            }
                            else
                            {
                                //记录登录日志
                                logs.add(name, userIp, city, true);
                                context.Response.ContentType = "text/html";
                                //context.Response.Write(JsonUtil.ToJson(new
                                //{
                                //    success = true,
                                //    msg = "登录成功！"
                                //}));
                                DateTime dateCookieExpires;  //cookie有效期
                                switch (remember)
                                {
                                    case "notremember":
                                        dateCookieExpires = new DateTime(9999, 12, 31);   //默认时间
                                        break;
                                    case "oneday":
                                        dateCookieExpires = DateTime.Now.AddDays(1);
                                        break;
                                    case "sevenday":
                                        dateCookieExpires = DateTime.Now.AddDays(7);
                                        break;
                                    case "onemouth":
                                        dateCookieExpires = DateTime.Now.AddDays(30);
                                        break;
                                    case "oneyear":
                                        dateCookieExpires = DateTime.Now.AddDays(365);
                                        break;
                                    default:
                                        dateCookieExpires = new DateTime(9999, 12, 31);
                                        break;
                                }
                                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                                (
                                    2,
                                    currentUser.userName,
                                    DateTime.Now,
                                    dateCookieExpires,
                                    false,
                                    new JavaScriptSerializer().Serialize(currentUser)  //序列化当前用户对象
                                );
                                string encTicket = FormsAuthentication.Encrypt(ticket);
                                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                                if (dateCookieExpires != new DateTime(9999, 12, 31))    //不是默认时间才设置过期时间，否则会话cookie
                                    cookie.Expires = dateCookieExpires;
                                context.Response.Cookies.Add(cookie);
                                context.Response.WriteFile("~/index.html");                                
                            }
                            break;
                        }
                    case "logout":
                        FormsAuthentication.SignOut();
                        HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                        DateTime now = DateTime.Now;
                        myCookie.Expires = now.AddYears(-2);//时间设置负数就能删除
                        HttpContext.Current.Response.Cookies.Add(myCookie);
                        context.Response.Write(JsonUtil.ToJson(new
                        {
                            success = true,
                            msg = "退出成功！"
                        }));
                        
                        break;
                    default:
                        context.Response.Write(JsonUtil.ToJson(new
                        {
                            success = false,
                            msg = "参数错误！"
                        }));                        
                        break;
                }
            }
            catch (Exception ex)
            {
                string msg = JsonUtil.StringFilter(ex.Message);
                context.Response.Write(JsonUtil.ToJson(new
                {
                    success = false,
                    msg = msg
                }));                      
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}